package com.wxl52d41.config;

import com.alibaba.fastjson.JSON;
import com.wxl52d41.exception.BusinessException;
import com.wxl52d41.result.Result;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;

/**
 * @ClassName: OpenFeignErrorDecoder
 * @Description: 解决Feign的异常包装，统一返回结果
 * @Author wxl
 * @Date 2023-08-26
 * @Version 1.0.0
 **/
@Configuration
public class OpenFeignErrorDecoder implements ErrorDecoder {
    /**
     * Feign异常解析
     *
     * @param methodKey 方法名
     * @param response  响应体
     * @return {@link Exception }
     * @Author wxl
     * @Date 2023-08-26
     **/
    @SneakyThrows
    @Override
    public Exception decode(String methodKey, Response response) {
        //获取数据
        String body = Util.toString(response.body().asReader(Charset.defaultCharset()));
        Result<?> result = JSON.parseObject(body, Result.class);
        if (!result.isSuccess()) {
            return new BusinessException(result.getStatus(), result.getMessage());
        }        return new BusinessException(500, "Feign client 调用异常");
    }

}
